package com.myschool.server.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.myschool.common.exception.ApplicationException;
import org.springframework.stereotype.Repository;

import com.myschool.server.dao.UserDao;
import com.myschool.server.dao.support.BaseEntityDaoHibernate;
import com.myschool.server.model.User;
import com.myschool.server.model.UserType;

@Repository
public class UserDaoImpl extends BaseEntityDaoHibernate<User> implements
		UserDao {

	public UserDaoImpl() {
		super(User.class);

	}

	@Override
	public boolean validateUserLogin(User user) {

		List<User> result = getHibernateTemplate().find(
				"from User where username= ? and password = ? ",
				new Object[] { user.getUsername(), user.getPassword() });

		return ((result == null || result.isEmpty()) ? false : true);
	}

	@Override
	public User retrieveUser(User user) {
		List<User> userList = new ArrayList<User>();

		userList = getHibernateTemplate().find(
				"from User where username= ? and password = ? ",
				new Object[] { user.getUsername(), user.getPassword() });

		// if a user exists then return that user, otherwise return false
		if (!userList.isEmpty()) {
			return userList.get(0);
		} else {
			return null;
		}
	}

	@Override
	public User retrieveUserByEmail(String email) throws ApplicationException {

		List<User> users = getHibernateTemplate().find(
				" from User user where user.address.contact.email= ? ", email);

		if (users != null && !users.isEmpty()) {

			return users.get(0);
		} else {

			throw new ApplicationException("Email not found");
		}

	}
	@Override
	public List<User> retrieveUserByType(UserType userType)
	{
 
		List<User> users = getHibernateTemplate().find(
				" from User user where user.type = ?" ,userType);
//TODO have to filter on usertype
		return users;
	}

	@Override
	public List<User> retrieveStudentBySection(Long section)
	{
 
		List<User> users = getHibernateTemplate().find(
				" from User user where user.type = ? and user.section.entityId=?" ,UserType.STUDENT, section);
//TODO have to filter on usertype
		return users;
	}

}
